﻿using MESDataAccess;
using MESDemoForYdet.Models;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;

namespace MESDemoForYdet.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        Param systemParam;
        MESInterface mes;
        #endregion
        #region 属性
        private string _title = "MESDemoForYdet";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }
        private string messageStr = string.Empty;
        public string MessageStr
        {
            get { return messageStr; }
            set { SetProperty(ref messageStr, value); }
        }
        private string barcode = string.Empty;
        public string Barcode
        {
            get { return barcode; }
            set { SetProperty(ref barcode, value); }
        }
        private string lazerPcCode;
        public string LazerPcCode
        {
            get { return lazerPcCode; }
            set { SetProperty(ref lazerPcCode, value); }
        }
        private string lazerStationNo;
        public string LazerStationNo
        {
            get { return lazerStationNo; }
            set { SetProperty(ref lazerStationNo, value); }
        }
        private int lazerPointCount;
        public int LazerPointCount
        {
            get { return lazerPointCount; }
            set {
                if (value > 0 && value < 100)
                {
                    SetProperty(ref lazerPointCount, value);
                }
            }
        }
        private string heatRivetPcCode;
        public string HeatRivetPcCode
        {
            get { return heatRivetPcCode; }
            set { SetProperty(ref heatRivetPcCode, value); }
        }
        private string heatRivetStationNo;
        public string HeatRivetStationNo
        {
            get { return heatRivetStationNo; }
            set { SetProperty(ref heatRivetStationNo, value); }
        }
        private int heatRivetPointCount;
        public int HeatRivetPointCount
        {
            get { return heatRivetPointCount; }
            set { SetProperty(ref heatRivetPointCount, value); }
        }
        private bool isBusy = false;
        public bool IsBusy
        {
            get { return isBusy; }
            set { SetProperty(ref isBusy, value); }
        }
        #endregion
        #region 命令绑定
        private DelegateCommand appLoadedEventCommand;
        public DelegateCommand AppLoadedEventCommand =>
            appLoadedEventCommand ?? (appLoadedEventCommand = new DelegateCommand(ExecuteAppLoadedEventCommand));
        private DelegateCommand appClosedEventCommand;
        public DelegateCommand AppClosedEventCommand =>
            appClosedEventCommand ?? (appClosedEventCommand = new DelegateCommand(ExecuteAppClosedEventCommand));
        private DelegateCommand lazerUploadCommand;
        public DelegateCommand LazerUploadCommand =>
            lazerUploadCommand ?? (lazerUploadCommand = new DelegateCommand(ExecuteLazerUploadCommand));
        private DelegateCommand heatRivetUploadCommand;
        public DelegateCommand HeatRivetUploadCommand =>
            heatRivetUploadCommand ?? (heatRivetUploadCommand = new DelegateCommand(ExecuteHeatRivetUploadCommand));

        async void ExecuteHeatRivetUploadCommand()
        {
            IsBusy = true;
            await Task.Run(() => {
                try
                {
                    HeatRivetMaster heatRivetMaster = new HeatRivetMaster();
                    heatRivetMaster.Barcode = Barcode;
                    heatRivetMaster.TestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    heatRivetMaster.PcCode = HeatRivetPcCode;
                    heatRivetMaster.StationNo = HeatRivetStationNo;
                    heatRivetMaster.Result = 1;
                    heatRivetMaster.ErrorCode = string.Empty;
                    heatRivetMaster.Remark = string.Empty;
                    //热铆 主表
                    long masterId = -1;
                    var uploadResult = mes.dataUploadGetAutoID("heat_rivet_master", "BARCODE,TEST_TIME,PC_CODE,STATION_NO,RESULT,ERROR_CODE,REMARK",
                                    $"'{heatRivetMaster.Barcode}', '{heatRivetMaster.TestTime}', '{heatRivetMaster.PcCode}', '{heatRivetMaster.StationNo}', '{heatRivetMaster.Result}', '{heatRivetMaster.ErrorCode}','{heatRivetMaster.Remark}'", out masterId);
                    if (uploadResult.IndexOf("ERR:") >= 0)
                    {
                        addMessage("热铆数据上传失败1:" + uploadResult);
                        return;
                    }
                    if (masterId > 0) //说明插入主表成功
                    {
                        HeatRivetDetail[] heatRivetDetails = new HeatRivetDetail[HeatRivetPointCount];
                        for (int i = 0; i < heatRivetDetails.Length; i++)
                        {
                            var _heatRivetDetail = new HeatRivetDetail();
                            _heatRivetDetail.MasterId = masterId.ToString();
                            _heatRivetDetail.Barcode = Barcode;
                            _heatRivetDetail.TestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            _heatRivetDetail.PcCode = LazerPcCode;
                            _heatRivetDetail.StationNo = LazerStationNo;
                            _heatRivetDetail.Result = 1;
                            _heatRivetDetail.ErrorCode = string.Empty;
                            _heatRivetDetail.Remark = string.Empty;
                            _heatRivetDetail.ItemName = $"{i}";
                            _heatRivetDetail.ItemType = "temperature";
                            Random rd = new Random();
                            var _v = rd.Next(50);
                            _heatRivetDetail.ItemValue = $"{180 + _v/10.0:f1}";
                            _heatRivetDetail.UnitName = "℃";
                            heatRivetDetails[i] = _heatRivetDetail;
                        }

                        string _content = string.Empty;
                        for (int i = 0; i < heatRivetDetails.Length; i++)
                        {
                            _content += $"{heatRivetDetails[i].MasterId} ,'{heatRivetDetails[i].Barcode}', '{heatRivetDetails[i].TestTime}', '{heatRivetDetails[i].PcCode}', '{heatRivetDetails[i].StationNo}', '{heatRivetDetails[i].Result}', " +
                            $"'{heatRivetDetails[i].ErrorCode}','{heatRivetDetails[i].Remark}','{heatRivetDetails[i].ItemName}','{heatRivetDetails[i].ItemValue}','{heatRivetDetails[i].ItemType}','{heatRivetDetails[i].UnitName}'";
                            if (i < heatRivetDetails.Length - 1)
                            {
                                _content += ";";
                            }
                        }

                        //热铆 主表对应的明细表
                        uploadResult = mes.dataUpload("heat_rivet_detail", "MASTER_ID,BARCODE,TEST_TIME,PC_CODE,STATION_NO,RESULT,ERROR_CODE,REMARK,ITEM_NAME,ITEM_VALUE,ITEM_TYPE,UNIT_NAME",
                            _content);
                        if (uploadResult.IndexOf("ERR:") >= 0)
                        {
                            addMessage("热铆数据上传失败2:" + uploadResult);                      
                        }
                        else
                        {
                            addMessage("热铆数据上传成功:" + uploadResult);
                        }
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                }
            });
            IsBusy = false;
        }
        async void ExecuteLazerUploadCommand()
        {
            IsBusy = true;
            await Task.Run(() => {
                try
                {
                    Lazer[] lazers = new Lazer[LazerPointCount];
                    for (int i = 0; i < lazers.Length; i++)
                    {
                        var _lazer = new Lazer();
                        _lazer.Barcode = Barcode;
                        _lazer.TestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        _lazer.PcCode = LazerPcCode;
                        _lazer.StationNo = LazerStationNo;
                        _lazer.Result = 1;
                        _lazer.ErrorCode = string.Empty;
                        _lazer.Remark = string.Empty;
                        Random rd = new Random();
                        var _v = rd.Next(50);
                        _lazer.Power = 450 + _v / 10.0;
                        _lazer.Speed = 200;
                        _v = rd.Next(100);
                        _lazer.FocusDistance = 270 - 5 + (_v - 10) / 100.0;
                        _lazer.Height = 5 + (_v - 10) / 100.0;
                        _lazer.WeldPoint = i < lazers.Length / 2 ? $"LP{i}" : $"RP{i - lazers.Length / 2}";
                        lazers[i] = _lazer;
                    }
                    //CCS MES上传  
                    //激光
                    string _content = string.Empty;
                    for (int i = 0; i < lazers.Length; i++)
                    {
                        _content += $"'{lazers[i].Barcode}', '{lazers[i].TestTime}', '{lazers[i].PcCode}', '{lazers[i].StationNo}', '{lazers[i].Result}', '{lazers[i].ErrorCode}','', '{lazers[i].Power:f1}', '{lazers[i].Speed}', '{lazers[i].FocusDistance:f2}', '{lazers[i].Height:f2}', '{lazers[i].WeldPoint}'";
                        if (i < lazers.Length - 1)
                        {
                            _content += ";";
                        }
                    }
                    string uploadResult = mes.dataUpload("laser", "BARCODE,TEST_TIME,PC_CODE,STATION_NO,RESULT,ERROR_CODE,REMARK,POWER,SPEED,FOCUS_DISTANCE,HEIGHT,WELD_POINT",
                                    _content);
                    if (uploadResult.IndexOf("ERR:") >= 0)
                    {
                        addMessage("激光数据上传失败:" + uploadResult);                       
                    }
                    else
                    {
                        addMessage("激光数据上传成功:" + uploadResult);
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                }
            });
            IsBusy = false;
        }
        void ExecuteAppClosedEventCommand()
        {
            try
            {
                if (systemParam == null)
                {
                    systemParam = new Param();
                }
                systemParam.Barcode = Barcode;
                systemParam.LazerPcCode = LazerPcCode;
                systemParam.LazerStationNo = LazerStationNo;
                systemParam.LazerPointCount = LazerPointCount;
                systemParam.HeatRivetPcCode = HeatRivetPcCode;
                systemParam.HeatRivetStationNo = HeatRivetStationNo;
                systemParam.HeatRivetPointCount = HeatRivetPointCount;
                string jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"), jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void ExecuteAppLoadedEventCommand()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
                Barcode = systemParam.Barcode;

                LazerPcCode = systemParam.LazerPcCode;
                LazerStationNo = systemParam.LazerStationNo;
                LazerPointCount = systemParam.LazerPointCount;
                HeatRivetPcCode = systemParam.HeatRivetPcCode;
                HeatRivetStationNo = systemParam.HeatRivetStationNo;
                HeatRivetPointCount = systemParam.HeatRivetPointCount;

                mes = new MESInterface();
                addMessage("软件加载完成");
            }
            catch (Exception ex)
            {
                addMessage(ex.Message);
            }
            
        }
        #endregion
        #region 构造函数
        public MainWindowViewModel()
        {
            NlogConfig();
        }
        #endregion
        #region 功能函数
        private void NlogConfig()
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "${basedir}/logs/${shortdate}.log", Layout = "${longdate}|${level:uppercase=true}|${message}" };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            // Rules for mapping loggers to targets            
            config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile);

            // Apply config           
            NLog.LogManager.Configuration = config;
        }
        private void addMessage(string str)
        {
            logger.Debug(str);
            string[] s = MessageStr.Split('\n');
            if (s.Length > 1000)
            {
                MessageStr = "";
            }
            if (MessageStr != "")
            {
                MessageStr += "\n";
            }
            MessageStr += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + str;
        }
        #endregion
    }
}
